import { getToken, clearToken } from './auth.js'

const DEFAULT_HEADERS = {
    'Content-Type': 'application/json',
}

const API_BASE_URL =
    import.meta.env?.VITE_API_BASE_URL || ''

/**
 * 统一的请求封装
 * @param {string} endpoint - 请求路径
 * @param {RequestInit} options - fetch 选项
 */
async function apiRequest(endpoint, options = {}) {
    const token = getToken()
    const headers = new Headers(options.headers || {})

    // 合并默认头
    Object.entries(DEFAULT_HEADERS).forEach(([key, value]) => {
        if (!headers.has(key) && options?.body) {
            headers.set(key, value)
        }
    })

    if (token) {
        headers.set('Authorization', `Bearer ${token}`)
    }

    const url = `${API_BASE_URL}${endpoint}`
    console.log(`apiRequest: 请求 URL: ${url}`)
    console.log(`apiRequest: Token 状态: ${token ? '存在' : '不存在'}`)

    const response = await fetch(url, {
        ...options,
        headers,
        credentials: 'include',
    }).catch((error) => {
        console.error('网络请求失败:', error)
        throw error
    })

    console.log(`apiRequest: 响应状态: ${response.status} ${response.statusText}`)

    if (response.status === 401) {
        clearToken()
        throw new Error('未授权或登录已过期')
    }

    let payload = null
    try {
        payload = await response.json()
        console.log('apiRequest: 响应数据:', payload)
    } catch (error) {
        console.warn('响应不是有效的JSON:', error)
        if (!response.ok) {
            throw new Error(response.statusText || '请求失败')
        }
        return null
    }

    if (!response.ok) {
        const message = payload?.message || response.statusText
        throw new Error(message || '请求失败')
    }

    // 统一处理后端 { code, data } 格式
    if (payload && typeof payload === 'object') {
        if ('code' in payload) {
            console.log(`apiRequest: 响应 code: ${payload.code}`)
            if (payload.code !== 200) {
                throw new Error(payload.message || '请求失败')
            }
            if ('data' in payload) {
                console.log('apiRequest: 返回 data 字段:', payload.data)
                return payload.data
            }
        }
    }

    console.log('apiRequest: 返回完整 payload:', payload)
    return payload
}

/**
 * 获取学习单词列表
 * @param {number} limit
 */
export async function fetchLearnWords(limit = 10) {
    const data = await apiRequest(`/api/study/quiz/new?limit=${limit}`, {
        method: 'GET',
    })

    if (Array.isArray(data)) {
        return data
    }

    if (data && Array.isArray(data.words)) {
        return data.words
    }

    return []
}

/**
 * 获取复习单词列表
 * @param {number} limit
 */
export async function fetchReviewWords(limit = 10) {
    const data = await apiRequest(`/api/study/review?limit=${limit}`, {
        method: 'GET',
    })

    if (Array.isArray(data)) {
        return data
    }

    if (data && Array.isArray(data.words)) {
        return data.words
    }

    return []
}

/**
 * 更新复习记录
 * @param {number} wordId
 * @param {'know'|'blur'|'forget'} confidence
 */
export async function updateReviewRecord(wordId, confidence) {
    const body = {
        wordId,
        mode: 'review',
        confidence,
    }

    const data = await apiRequest('/api/study/review/update', {
        method: 'POST',
        body: JSON.stringify(body),
    })

    return data || {}
}

/**
 * 更新学习记录（使用新接口 /api/study/quiz/check）
 * @param {number} wordId
 * @param {'know'|'forget'} confidence
 */
export async function updateLearnRecord(wordId, confidence) {
    const body = {
        wordId,
        mode: 'learn',
        confidence,
    }

    const data = await apiRequest('/api/study/quiz/check', {
        method: 'POST',
        body: JSON.stringify(body),
    })

    return data || {}
}

/**
 * 获取单词详情
 * @param {number} wordId
 */
export async function fetchWordDetail(wordId) {
    if (!wordId) return null

    const data = await apiRequest(`/api/study/word/${wordId}`, {
        method: 'GET',
    })

    return data || null
}

/**
 * 获取小结数据
 * @param {number[]} wordIds
 * @param {'learn'|'review'} mode
 */
export async function fetchWordSummary(wordIds = [], mode = 'learn') {
    const data = await apiRequest(`/api/study/summary?mode=${mode}`, {
        method: 'POST',
        body: JSON.stringify({ wordIds }),
    })

    return data || {}
}

/**
 * 获取拼写单词列表
 * @param {number[]} wordIds
 * @param {'learn'|'review'} mode
 */
export async function fetchSpellingWords(wordIds = [], mode = 'learn') {
    const data = await apiRequest(`/api/study/spelling?mode=${mode}`, {
        method: 'POST',
        body: JSON.stringify({ wordIds }),
    })

    if (Array.isArray(data)) {
        return data
    }

    return Array.isArray(data?.words) ? data.words : []
}

/**
 * 获取仪表盘数据
 */
export async function fetchDashboard() {
    try {
        console.log('fetchDashboard: 开始调用 apiRequest')
        const data = await apiRequest('/api/study/dashboard', {
            method: 'GET',
        })
        console.log('fetchDashboard: apiRequest 返回的数据:', data)
        
        // 如果返回的数据为空或格式不正确，返回默认值
        if (!data || typeof data !== 'object') {
            console.warn('fetchDashboard: 数据格式不正确，返回默认值')
            return {
                wordbook: {
                    id: null,
                    name: '未选择词书',
                    coverUrl: '',
                    wordCount: 0,
                },
                progress: {
                    learnedWords: 0,
                    totalWords: 0,
                    progressPercent: 0,
                },
                statistics: {
                    todayTotalWords: 0,
                    todayDuration: 0,
                    totalLearnedWords: 0,
                    totalDuration: 0,
                },
            }
        }
        
        return data
    } catch (error) {
        console.error('fetchDashboard: 请求失败', error)
        throw error
    }
}

/**
 * 保存学习时长
 * @param {number} duration - 学习时长（分钟）
 * @param {string} studyDate - 学习日期（可选，默认今天）
 */
export async function saveStudySession(duration, studyDate = null) {
    const body = {
        duration: duration,
    }
    
    if (studyDate) {
        body.studyDate = studyDate
    }
    
    const data = await apiRequest('/api/study/session', {
        method: 'POST',
        body: JSON.stringify(body),
    })
    
    return data || {}
}

/**
 * 获取词书列表
 */
export async function fetchWordbooks() {
    const data = await apiRequest('/api/library/books', {
        method: 'GET',
    })
    
    // 如果返回的是对象且有 data 字段，返回 data
    if (data && typeof data === 'object' && !Array.isArray(data) && Array.isArray(data.data)) {
        return data.data
    }
    
    // 如果直接是数组，返回数组
    if (Array.isArray(data)) {
        return data
    }
    
    // 否则返回空数组
    return []
}

/**
 * 获取用户的学习任务列表（用于获取学过的词书）
 */
export async function fetchStudyTasks() {
    const data = await apiRequest('/api/study/tasks', {
        method: 'GET',
    })
    
    // 如果返回的是对象且有 data 字段，返回 data
    if (data && typeof data === 'object' && !Array.isArray(data) && Array.isArray(data.data)) {
        return data.data
    }
    
    // 如果直接是数组，返回数组
    if (Array.isArray(data)) {
        return data
    }
    
    // 否则返回空数组
    return []
}

/**
 * 切换当前学习的词书
 * @param {number} wordbookId - 词书ID
 */
export async function switchWordbook(wordbookId) {
    const data = await apiRequest('/api/study/switch-wordbook', {
        method: 'POST',
        body: JSON.stringify({ wordbookId }),
    })
    
    return data
}

export { apiRequest }